package cn.boodqian.d3surveyor;

import java.util.HashMap;
import java.util.Map;

import cn.boodqian.d3surveyor.D3DB.Lang;
import cn.boodqian.util.Log;
import android.support.v4.app.Fragment;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.SimpleAdapter;
import android.widget.Spinner;

public abstract class D3Activity extends FragmentActivity implements OnClickListener, OnItemSelectedListener {

	protected D3DB m_DB;
	protected Spinner m_Profession;
	protected Button m_Back;
	protected Spinner m_Setting;
	private int m_SpinnerCount = 2;
	private int m_SelectCount = 0;
	
	protected PackageInfo m_PackageInfo;
	
    protected void onCreate(Bundle savedInstanceState, int layoutID) {
        super.onCreate(savedInstanceState);
        
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(layoutID);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar_fragment);

        try {
        	m_PackageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        } catch (NameNotFoundException e) {
        	m_PackageInfo = null;
        	Log.wtf("Cannot get package info:\n"+e.toString());
        }
        
        m_Profession = (Spinner)findViewById(R.id.spinner_titlebar_profession);
        m_Back = (Button)findViewById(R.id.btn_titlebar_back);
        m_Setting = (Spinner)findViewById(R.id.spinner_titlebar_lang);
         
        m_DB = D3DB.getInstance(this);
        m_Profession.setAdapter(m_DB.cursorToAdapter(m_DB.m_pTypeCursor, R.layout.profession_spinner));
        SimpleAdapter adapter = new SimpleAdapter(this, m_DB.selectLang(),
        		R.layout.profession_spinner,
        		new String[]{"name"}, new int[]{android.R.id.text1}
        		);
        adapter.setDropDownViewResource(R.layout.spinner_dropdown);
        m_Setting.setAdapter(adapter);
        
        m_Back.setOnClickListener(this);
        m_Profession.setOnItemSelectedListener(this);
        m_Setting.setOnItemSelectedListener(this);
        
        if(m_DB.getProfessionType()==0)
        	m_DB.setProfessionType(m_DB.getDefaultPType());
    }

    public void onClick(View v) {
    	Log.i("titlebar clicked="+v.getId());
    	Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_magic_property);
    	switch(v.getId()) {
    	case R.id.btn_titlebar_back:
    		finish();
    		break;
    	}

    }

	public void onItemSelected(AdapterView<?> parent, View v, int pos,
			long id) {
		if(m_SelectCount<m_SpinnerCount) {
			m_SelectCount++;
			Log.i("select count="+m_SelectCount);
			return;
		}
		Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_magic_property);
		switch(parent.getId()) {
		case R.id.spinner_titlebar_profession:
			Cursor c = (Cursor) parent.getItemAtPosition(pos);
			int pType = m_DB.getCursorType(c);
			if (m_DB.getProfessionType()==pType) break;
			
			if(fragment!=null) {
				((MagicPropertyFragment)fragment).onChangeProfession(pType);
			} else {
				m_DB.setProfessionType(pType);
			}
			Log.i("new profession="+m_DB.getProfessionType());
			break;
		case R.id.spinner_titlebar_lang:
			Map<String,String> m = (Map)parent.getItemAtPosition(pos);
    		m_DB.refreshDataByLanguage(D3DB.Lang.valueOf(m.get("lang")));
    		m_Profession.setAdapter(m_DB.cursorToAdapter(m_DB.m_pTypeCursor, R.layout.profession_spinner));
    		updateProfession();
    		if(fragment!=null) {
    			((MagicPropertyFragment)fragment).updateLang();
    		}
    		break;
		}
		
	}

	public void onNothingSelected(AdapterView<?> parent) {
		
	}
	
	private void updateProfession() {
		for (int i = 0; i < m_Profession.getCount(); i++) {
			Cursor value = (Cursor) m_Profession.getItemAtPosition(i);
			if( m_DB.getProfessionType() == m_DB.getCursorType(value) ) {
				m_Profession.setSelection(i, true);
				break;
			}
		}
	}
	
	private void updateSetting() {
		for (int i = 0; i < m_Setting.getCount(); i++) {
			HashMap<String, String> value = (HashMap<String, String>) m_Setting.getItemAtPosition(i);
			if( m_DB.getLang() == D3DB.Lang.valueOf(value.get("lang")) ) {
				m_Setting.setSelection(i, true);
				break;
			}
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		
		Log.i("resume profession="+m_DB.getProfessionType());
		// Select the current choice for mSpinnerPart
		updateProfession();
		updateSetting();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);
		return true;
	}
	
		@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.menu_fixdb:
			String fixdb_msg=null;
			if(m_DB.getDBHelper().copyDatabase()) {
				fixdb_msg = getString(R.string.fixdb_success);
			} else {
				fixdb_msg = getString(R.string.fixdb_failed);
			}
			new AlertDialog.Builder(this)
			.setTitle(getString(R.string.info))
			.setMessage(fixdb_msg)
			.setPositiveButton(getString(R.string.close), null)
			.show();
			return true;
		case R.id.menu_feedback:
			final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
			String title = String.format(getString(R.string.feedback_title), getString(R.string.app_name), m_PackageInfo.versionName);
			emailIntent .setType("message/rfc822");
			//emailIntent .setType("plain/text"); 
			emailIntent .putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"boodweb@gmail.com"});     
			emailIntent .putExtra(android.content.Intent.EXTRA_SUBJECT, title);     
			//emailIntent .putExtra(android.content.Intent.EXTRA_TEXT, yourBodyText);     
			startActivity(Intent.createChooser(emailIntent, "Send mail..."));
			return true;
		case R.id.menu_about:
			String app_version = String.format("%s v%s",
					getString(R.string.app_name),
					m_PackageInfo==null?"unkown":m_PackageInfo.versionName);
			String db_version = String.format(getString(R.string.db_version), m_DB.getDBHelper().getReadableDatabase().getVersion());
			String author_info = getString(R.string.author_info);
			new AlertDialog.Builder(this)
			.setTitle(getString(R.string.about))
			.setMessage(app_version+"\n"+db_version+"\n\n"+author_info)
			.setPositiveButton(getString(R.string.close), null)
			.setIcon(R.drawable.ic_launcher)
			.show();

			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
}
